import { useMessage } from 'naive-ui'
import { useStore } from '@/store'
import { formatDate } from '@/utils'

export default () => {
  const message = useMessage()
  const store = useStore()
  return {
    async exportSheets(action: string, requestData: Record<string, any>, fileName?: string) {
      try {
        const blob = await store.dispatch(action, requestData)
        if (blob instanceof Blob) {
          // 默认文件后缀
          let suffix = '.xls'
          const blobTypeList: any = {
            xls: 'application/vnd.ms-excel',
            xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            csv: 'text/csv'
          }
          // 根据blob.type，匹配文件后缀
          for (const key in blobTypeList) {
            if (blob?.type.includes(blobTypeList[key])) {
              suffix = `.${key}`
            }
          }
          const a = document.createElement('a')
          const finalFileName = fileName ? fileName : `【导出文件】${formatDate(new Date(), 'yyyyMMddhhmmss')}`
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            // 兼容ie浏览器下数据流处理
            window.navigator.msSaveOrOpenBlob(blob, `${finalFileName}${suffix}`)
          } else {
            a.href = URL.createObjectURL(blob)
            a.download = `${finalFileName}${suffix}`
            a.style.display = 'none'
            document.body.appendChild(a)
            a.click()
            a.remove()
          }
          message.success('导出成功')
        } else {
          Promise.reject()
        }
      } catch (e: any) {
        message.error(e)
      }
    }
  }
}
